import * as config from './config.js';


export const jumpTo = (url, param = {}, needVavigateTo = true) => {
  let pageList = getCurrentPages();
  url = /\?/.test(url) ? url : `${url}?`;
  for (let key in param) {
    url += `${key}=${param[key]}&`
  }
  if (param && JSON.stringify(param) != '{}') {
    url = url.substr(0, url.length - 1);
  }

  if (pageList.length < 10 && needVavigateTo) {
    wx.navigateTo({ url: url });
  } else {
    wx.redirectTo({ url: url });
  }
}

Promise.prototype.finally = function (callback) {
  let P = this.constructor;
  return this.then(
    value => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => { throw reason })
  );
};
export const rpxToPx = (rpx) => {
  let windowWidth = wx.getSystemInfoSync().windowWidth;
  return parseInt(rpx / 750 * windowWidth);
};

const responseFail = {
  code: -1,
  message: '服务器繁忙，请稍后重试'
};

const getCookie = () => {
  return wx.getStorageSync(config.COOKIE_KEY);
}


const send = (url, param, method = 'GET', isLogin = false) => {
  let requestURL = url;
  if (!/^http/.test(url)) {
    requestURL = /^\//.test(url) ?
      `${config.baseURL}${url}` : `${config.baseURL}/${url}`;
  }
  let header = {};
  let obj = {}
  if (!isLogin) {
    header["x-token"] = getCookie() || '';
  }
  return new Promise((resolve, reject) => {
    wx.request({
      header: header,
      method: method,
      url: requestURL,
      data: param,
      success(res) {
        log(res);
        if (res.statusCode !== 200) {
          reject(res.data || responseFail);
        } else {
          if (isLogin && res.data) {
            let data = res.data || {}
            let token = data.token;
          
            wx.setStorageSync(config.COOKIE_KEY, token);
           
          }
          resolve(res.data === undefined ? {} : res.data);
        }
      },
      fail(error) {
        log(error);
        reject(responseFail);
      }
    })
  });
}

export const doGet = (url, param = {}) => {
  return send(url, param, 'GET');
}

export const doPost = (url, param = {}) => {
  return send(url, param, 'POST');
}

export const doPut = (url, param = {}) => {
  return send(url, param, 'PUT');
}

export const doDelete = (url, param = {}) => {
  return send(url, param, 'DELETE');
}

export const doLogin = (url, param = {}) => {
  return send(url, param, 'POST', true);
}

export const log = (msg) => {
  if (!config.isDev) { return; }
  console.log(msg);
};


export const showMsg = (msg = '服务器繁忙，请稍后重试') => {
  let info = msg;
  if (typeof (msg) !== 'string') {
    info = (msg || {}).message || '服务器繁忙，请稍后重试'
  }
  wx.showToast({
    title: info,
    icon: 'none'
  })
}